package com.example.roam.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;

import androidx.annotation.Nullable;

/**
 * Create By Visen
 * Date: 2021/10/26
 * 不带有边框的圆形图片
 */
public class CircleImageView extends androidx.appcompat.widget.AppCompatImageView {

    public CircleImageView(Context context) {
        super(context);
    }

    public CircleImageView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public CircleImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        int size = Math.min(getMeasuredWidth(), getMeasuredHeight());         //由于是圆形，宽高应保持一致
        int mRadius = size / 2; //圆形图片的半径
        setMeasuredDimension(size, size); // 设置图片为正方形

        Paint mPaint = new Paint();//画笔
        Drawable drawable = getDrawable(); // 获取图片
        Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap(); // 从图片中获取位图
        BitmapShader bitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);  //初始化BitmapShader，传入bitmap对象
        /**
         * 创建着色器 设置着色模式
         * TileMode的取值有三种：
         *  CLAMP 拉伸  REPEAT 重复   MIRROR 镜像
         */
        float mScale = (mRadius * 2.0f) / Math.min(bitmap.getHeight(), bitmap.getWidth()); //计算缩放比例
        Matrix matrix = new Matrix();
        matrix.setScale(mScale, mScale);
        bitmapShader.setLocalMatrix(matrix);
        mPaint.setShader(bitmapShader);
        canvas.drawCircle(mRadius, mRadius, mRadius, mPaint);//画圆形，指定好坐标，半径，画笔
    }

}